<template>
  <div ref="el" class="code-editor"></div>
</template>

<script lang="ts" setup>
import { onMounted, nextTick, watch, PropType } from "vue";
import "./worker.ts";
import { useCodeEditor, useCompileCode, EditorOptions } from "./hooks.ts";

defineOptions({
  name: "CodeEditor",
});

const props = defineProps({
  // 就是code，代码
  modelValue: {
    type: String,
    required: true,
  },
  // monaco-editor的options
  options: {
    type: Object as PropType<EditorOptions>,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue"]);

// 给元素添加ref属性，值为el，同时我们定义 el 的 ref 数据 -> 这个el的ref数据就能获取到DOM元素
const { el, createEditor, updateEditorValue, getEditorValue } = useCodeEditor(
  props.options
);

onMounted(async () => {
  // 创建编辑器
  const editor = createEditor();
  // 将代码渲染上去
  updateEditorValue(props.modelValue);

  // 编辑器失焦事件
  editor.onDidBlurEditorWidget(() => {
    emit("update:modelValue", getEditorValue());
  });
});

watch(
  () => props.modelValue,
  () => {
    // 将代码渲染上去
    updateEditorValue(props.modelValue);
  }
  // 触发时机会早于mounted
  // {
  //   immediate: true,
  // }
);
</script>

<style scoped lang="scss">
.code-editor {
  height: 100%;
  min-height: 100px;
}
</style>
